package com.itqf.aop;

import com.alibaba.fastjson.JSON;
import com.itqf.entity.SysLog;
import com.itqf.service.SysLogService;
import com.itqf.utils.HttpContextUtils;
import com.itqf.utils.IPUtils;
import com.itqf.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/10/22
 * @Time: 上午9:36
 */
@Component
@Aspect  //切面
public class MyLogAspect {

    @Resource
    private SysLogService sysLogService;

    //@Pointcut(value = "execution(* com.itqf.service.*.*(..))")  方法
   //被com.itqf.aop.MyLog 注解修饰的方法 会被增强
    @Pointcut("@annotation(com.itqf.aop.MyLog)")//注解
    public  void  myPointcut(){

    }


    @AfterReturning("myPointcut()")
    //JoinPoint
    public  void after(JoinPoint joinPoint){
        String param = JSON.toJSONString(joinPoint.getArgs());
        //得到用户的操作行为
        //  @MyLog(value = "删除菜单",description = "使用假删除实现删除菜单")
       Class targetClass =  joinPoint.getTarget().getClass();
       MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
       Method method =  methodSignature.getMethod();
       String operation = null;
       if (method.isAnnotationPresent(MyLog.class)){
            MyLog myLog = method.getAnnotation(MyLog.class);
            String desc = myLog.description();
            if (desc==null||desc.equals("")){
               desc = myLog.value();
            }
           operation = desc;
       }

        String ip = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());

        SysLog sysLog = new SysLog();
        sysLog.setParams(param);
        sysLog.setOperation(operation);
        sysLog.setMethod(targetClass+method.getName());//com.itqf.controller.SysMenuController.delMenu
        sysLog.setIp(ip);
        sysLog.setCreateDate(new Date());
        sysLog.setUsername(ShiroUtils.getCurrentUser().getUsername());

        System.out.println("后置增强："+operation+targetClass+method.getName());

        sysLogService.saveLog(sysLog);

    }



}
